package com.hm.oper_monitor.ui.page.set;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import javax.swing.DefaultCellEditor;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.SwingConstants;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumnModel;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.hm.common.util.ResourceUtil;
import com.hm.common.util.SpringUtil;
import com.hm.oper_monitor.bean.ResourcesManager;
import com.hm.oper_monitor.constants.Constants;
import com.hm.oper_monitor.dao.ConfigDao;
import com.hm.oper_monitor.dao.busimonitor.BusiMonitorDao;
import com.hm.oper_monitor.pojo.Config;
import com.hm.oper_monitor.pojo.ConfigSql;
import com.sun.xml.internal.xsom.impl.scd.Iterators.Map;

@SuppressWarnings("serial")
public class SetPage extends JPanel {
	Logger logger = LoggerFactory.getLogger(SetPage.class);
	public static final String tip = "set";
	// 标题
	public static final String title = "系统配置";
	private static SetPage page;
	// 资源管理器
	private ResourcesManager rm;
	// 左侧配置列表
	private JTable configListTable;
	// 中间列表上部详细配置列表
	private JTable configDetailTable;
	// 中间列表下部字段配置列表
	private JTable configSqlTable;
	// 右侧展示选择列表
	private JTable configDisplayTable;
	// 配置DAO
	private ConfigDao configDao;
	// 业务列表显示DAO
	private BusiMonitorDao busiMonitorDao;
	// 左侧配置列表Model
	private ConfigListTableModel configListTableModel;
	// 中间列表上部详细配置列表Model
	private ConfigDetailTableModel configDetailTableModel;
	// 中间列表下部字段配置列表Model
	private ConfigSqlTableModel configSqlTableModel;
	// 右侧展示选择列表
	private ConfigDisplayTableModel configDisplayTableModel;
	// 左侧配置列表列名
	final String[] columnNames = { "业务编号", "业务名称" };
	// 中间列表上部详细配置列表列名
	final String[] detailColumnNames = { "监控配置字段", "配置字段名称", "监控配置" };
	// 中间列表下部字段配置列表列名
	final String[] detailSqlColumnNames = { "监控字段", "字段名称", "匹配条件", "匹配值" };
	// 右侧展示选择列表列名
	final String[] displayColumnNames = { "监控字段", "是否展示" };
	// 配置列表字段名，暂时隐藏了
	final String[] congfigFields = { "id", "config_name", "table_name", "phone", "message", "isSendSms", "time",
			"configSql", "count" };
	final String[] congfigSqlNames = { "业务编号", "业务名称", "委托单位代码", "业务代码", "清算日期", "交易码", "响应码", "监控时间" };

	final String[] congfigNames = { "业务编号", "业务名称", "监控表名", "运维人员电话号码", "异常短信发送内容",
			"是否发送监控信息 \r\n (填\"是\",\"yes\",\"true\"都为发送信息)", "监控时间", "SQL", "数量限制(和匹配字段功能一起使用)",
			"是否使用匹配字段 \r\n (填\"是\",\"yes\",\"true\"都为使用)" };
	final String[] congfigSqlFields = { "id", "config_name", "tran_dt", "tran_cd", "merch_id", "ope_cd", "rsp_cd",
			"time" };
	// 展示字段
	final String[] checkConfigDisplay = { "清算日期(TRAN_DT)", "交易码(TRAN_CD)", "委托单位代码(MERCH_ID)", "业务代码(OPE_CD)",
			"响应码(RSP_CD)", "中心流水号(TRAN_SQ)", "交易简称(TRAN_ABBR_NM)", "机构代码(INST_ID)", "机构类型(NODE_TYPE)",
			"前端流水号(SOLE_FRONT_SQ)", "渠道代码(CHNL_CD)", "交易时间戳(TIME_STAMP)", "交易状态(TRAN_STATE_CD)", "操作员(TLR_ID)",
			"账号(ACC_CARD_ID)", "交易金额(TRAN_AT)", "业务专号(PAY_ID)", "交易日志文件名(LOGFILE_NAME)", "交易日志单号(LOG_ID)",
			"交易耗时(TX_USE_TIME)", "响应描述(RET_DESC)", "前端服务器代码(SERVER_CD)" };
	// 左侧配置列表数据
	Object[][] rowData = new String[30][10];
	// 中间列表上部详细配置列表数据
	Object[][] configDetailData = new String[10][3];
	// 中间列表下部详细配置列表数据
	Object[][] configDetailSqlData = new String[10][4];
	// 右侧展示选择列表数据
	Object[][] configDisplayData = new Object[22][2];
	protected int row;
	protected int col;
	private JPanel configPanel = new JPanel();
	// 监控定时器
	private Timer timer = new Timer();
	// 监控条件MAP
	private HashMap<String, String> smsMap = new HashMap<String, String>();
	// 监控时间条件MAP（周期一天）
	private HashMap<String, Integer> smsTimeMap = new HashMap<String, Integer>();

	private SetPage() {
		rm = SpringUtil.getBean(ResourcesManager.class);
		configDao = SpringUtil.getBean(ConfigDao.class);
		busiMonitorDao = SpringUtil.getBean(BusiMonitorDao.class);

		setPage();
	}

	public static SetPage getPage() {
		if (page == null) {
			synchronized (SetPage.class) {
				if (page == null) {
					page = new SetPage();
				}
			}
		}
		return page;
	}

	public void setPage() {
		configDao.createTable();
		configDao.createSqlTable();
		// this.setPreferredSize(new Dimension(rm.getScreenViewProp().getScreenWidth() /
		// 3, rm.getScreenViewProp().getScreenHeight()));
		this.setLayout(new BorderLayout());
		this.setBounds(0, 0, rm.getScreenViewProp().getScreenWidth(), rm.getScreenViewProp().getScreenHeight());
		// 初始化头部三个按钮
		initButtonPanel();
		// 初始化左侧配置列表
		initConfigListTable();

		Config config = new Config();
		List<Config> dataList = configDao.selectPage(null);
		if (dataList != null && dataList.size() != 0) {
			config.setId(dataList.get(0).getId());
		}
		// 初始化中间详细信息配置
		initConfigTable(config);
		// 初始化右侧字段显示列表
		initConfigCheckList(config);
		// 开始监控
		startMonitor();
	}

	// 初始化中间详细信息配置
	public void initConfigTable(Config config) {
		configPanel.setLayout(new GridLayout(2, 1, 0, 0));
		this.add(configPanel, BorderLayout.CENTER);
		initConfigDetailTable(config);
		initConfigSqlTable(config);

	}

	// 初始化头部三个按钮
	public void initButtonPanel() {
		JPanel p = new JPanel();
		p.setLayout(new FlowLayout(FlowLayout.LEFT));

		JButton addBtn = new JButton("新增");
		Image addImage = ResourceUtil.getImage(this.getClass().getClassLoader(), "images/add.png");
		ImageIcon addIcon = new ImageIcon();
		addIcon.setImage(addImage);
		addIcon.setImage(addIcon.getImage().getScaledInstance(23, 23, Image.SCALE_DEFAULT));
		addBtn.setIcon(addIcon);
		// addBtn.setBounds(0, 0, 100, 160);

		JButton saveBtn = new JButton("保存");
		Image saveImage = ResourceUtil.getImage(this.getClass().getClassLoader(), "images/save.png");
		ImageIcon saveIcon = new ImageIcon();
		saveIcon.setImage(saveImage);
		saveIcon.setImage(saveIcon.getImage().getScaledInstance(23, 23, Image.SCALE_DEFAULT));
		saveBtn.setIcon(saveIcon);
		// saveBtn.setBounds(0, 0, 100, 160);

		JButton delBtn = new JButton("删除");
		Image delImage = ResourceUtil.getImage(this.getClass().getClassLoader(), "images/delete.png");
		ImageIcon delIcon = new ImageIcon();
		delIcon.setImage(delImage);
		delIcon.setImage(delIcon.getImage().getScaledInstance(23, 23, Image.SCALE_DEFAULT));
		delBtn.setIcon(delIcon);
		// delBtn.setBounds(0, 0, 100, 160);
		// 新增按钮监听，初始化所有详细配置
		addBtn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				for (int i = 0; i < congfigNames.length; i++) {
					String[] t = { congfigNames[i], "" };
					configDetailData[i] = t;
				}
				for (int i = 0; i < checkConfigDisplay.length; i++) {
					configDisplayData[i][0] = false;
				}
				for (int i = 0; i < configDetailSqlData.length; i++) {
					Object[] temp = configDetailSqlData[i];
					for (int j = 0; j < temp.length; j++) {
						configDetailSqlData[i][j] = "";
					}
				}
				// 监控数据Model更新
				configDetailTableModel.fireTableStructureChanged();
				configSqlTableModel.fireTableStructureChanged();
				configDisplayTableModel.fireTableStructureChanged();
			}
		});

		saveBtn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				// 把数据更新到config
				Config config = new Config();
				config.setConfigName(configDetailData[1][1].toString());
				config.setTableName(configDetailData[2][1].toString());
				config.setPhone(configDetailData[3][1].toString());
				config.setMessage(configDetailData[4][1].toString());
				config.setIsSendSms(configDetailData[5][1].toString());
				config.setTime(configDetailData[6][1].toString());
				config.setCount(configDetailData[8][1].toString());
				String isEdit = configDetailData[9][1].toString();
				config.setIsEdit(isEdit);
				String display = "";
				// 更新展示字段到config
				for (int i = 0; i < checkConfigDisplay.length; i++) {
					if (i == 0) {
						if ((Boolean) configDisplayData[i][0]) {
							display = display + "1";
						} else {
							display = display + "0";
						}
					} else {
						if ((Boolean) configDisplayData[i][0]) {
							display = display + ",1";
						} else {
							display = display + ",0";
						}
					}
				}
				config.setDisplay(display);
				String id = configDetailData[0][1].toString();
				// 下部字段匹配更新到configSql
				ConfigSql sqlConfig = new ConfigSql();
				if (id != null && !"".equals(id)) {
					config.setId(Integer.parseInt((String) id));
					sqlConfig.setId(Integer.parseInt((String) id));
				}
				
				if ("".equals(id) || id == null) {
					List<Config> p = configDao.selectPage(null);
					int index = p.size() - 1;
					if(index >= 0) {
						int sqlId = p.get(index).getId();
						sqlConfig.setId(sqlId + 1);
					}else {
						sqlConfig.setId(1);
					}
					
				}
				
				// 每次先删除再重新插入
				configDao.deleteSql(sqlConfig);
				for (int i = 0; i < configDetailSqlData.length; i++) {
					if (configDetailSqlData[i][0] != null && configDetailSqlData[i][0].toString() != "") {
						sqlConfig.setMonitorField(configDetailSqlData[i][0].toString());
						sqlConfig.setConfigName(config.getConfigName());
						if (sqlConfig.getId() > 0) {
							sqlConfig.setFieldName((String) configDetailSqlData[i][1]);
							sqlConfig.setExactMatch((String) configDetailSqlData[i][2]);
							sqlConfig.setValue((String) configDetailSqlData[i][3]);
							configDao.insertSql(sqlConfig);
						}
					}
				}
				Config c = new Config();
				c.setId(config.getId());
				// 根据字段拼接SQL
				List<ConfigSql> sqlList = configDao.selectSqlPage(c);
				String TSql = configDetailData[7][1].toString();
				boolean isSMMNTJNL = config.getTableName().contains("SMMNT_JNL") || config.getTableName().contains("smmnt_jnl")
						||TSql.contains("SMMNT_JNL") || TSql.contains("smmnt_jnl");
				boolean isEDIT = "是".equals(isEdit) || "1".equals(isEdit) || "true".equalsIgnoreCase(isEdit) || "YES".equalsIgnoreCase(isEdit) ||isEdit.contains("是");
				if(isEDIT || isSMMNTJNL) {
					String sql = "select * from " + config.getTableName() + " where 1=1 ";
					for (int i = 0; i < sqlList.size(); i++) {
						ConfigSql cs = sqlList.get(i);
						if (!"".equals(cs.getMonitorField()) && !"".equals(cs.getExactMatch()) && !"".equals(cs.getValue()))
							sql = sql + " and " + cs.getMonitorField() + " " + cs.getExactMatch() + " '" + cs.getValue()
									+ "' ";
					}
					if (config.getTableName().contains("SMMNT_JNL") || config.getTableName().contains("smmnt_jnl")) {
						sql = sql + "order by TIME_STAMP desc";
					}
					String isSendSms = config.getIsSendSms();
					config.setSelectSql(sql);
					// 只有选择了发送短信才拼接数量查询SQL
					if ("是".equals(isSendSms) || "1".equals(isSendSms) || "true".equals(isSendSms)
							|| "yes".equals(isSendSms) || "YES".equals(isSendSms)) {
						if (!"".equals(config.getCount()) && config.getCount() != null) {
							sql = "SELECT * FROM (SELECT count(*) num FROM (" + sql + " )) WHERE num " + config.getCount();
						}
					}
					if(isEDIT) {
						config.setConfigSql(sql);
					}else {
						config.setConfigSql(TSql);
					}
				}else {
					config.setSelectSql(TSql);
					config.setConfigSql(TSql);
				}
				
				// //如果填写过修改过sql则直接将
				// Config tc = new Config();
				// String tempId = configDetailData[0][1].toString();
				// if(!"".equals(tempId) && tempId != null) {
				// tc.setId(Integer.valueOf(id));
				// }
				// Config tempC = configDao.select(tc);
				// String cs = tempC.getConfigSql();
				// String displaySql = configDetailData[7][1].toString();
				// if(displaySql != null) {
				// if(!displaySql.equals(tempC.getConfigSql())) {
				//
				// }
				// }
				if (id != null && !"".equals(id)) {
					configDao.update(config);
				} else {
					configDao.insert(config);
				}
				// 重置监听Map
				Calendar rightNow = Calendar.getInstance();
				Integer year = rightNow.get(Calendar.YEAR);
				Integer month = rightNow.get(Calendar.MONTH) + 1; // 第一个月从0开始，所以得到月份＋1
				Integer day = rightNow.get(Calendar.DAY_OF_MONTH);
				Integer TimeNow24 = year + month + day;
				smsTimeMap.put("" + config.getId(), TimeNow24);
				smsMap.put("" + config.getId(), "0");
				initRowData();
				startMonitor();
				// 记录是否更新配置
				if (!rm.isUpdateBusi) {
					rm.setUpdateBusi(true);
				}
			}
		});
		// 删除某条数据刷新界面
		delBtn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				Config config = new Config();
				config.setId(Integer.parseInt((String) rowData[row][0]));
				configDao.delete(config);
				initRowData();
			}
		});

		p.setBounds(0, 0, rm.getScreenViewProp().getScreenWidth(), 300);
		p.add(addBtn);
		p.add(saveBtn);
		p.add(delBtn);
		this.add(p, BorderLayout.NORTH);
	}

	protected void initRowData() {
		List<Config> p = configDao.selectPage(null);
		rowData = null;
		rowData = new String[100][10];
		// 设置显示数据
		for (int i = 0; i < p.size(); i++) {
			Config config = p.get(i);
			String[] t = { ("" + config.getId()), config.getConfigName(), config.getTableName(), config.getPhone(),
					config.getMessage(), config.getIsSendSms(), config.getTime(), config.getConfigSql(),
					config.getCount(), config.getIsEdit(), config.getTranSq(), config.getDisplay() };
			rowData[i] = t;
		}
		configListTableModel.fireTableStructureChanged();
	}

	// 初始化左侧配置列表
	public void initConfigListTable() {
		List<Config> p = configDao.selectPage(null);
		for (int i = 0; i < p.size(); i++) {
			Config config = p.get(i);
			String[] t = { ("" + config.getId()), config.getConfigName(), config.getTableName(), config.getPhone(),
					config.getMessage(), config.getIsSendSms(), config.getTime(), config.getConfigSql(),
					config.getCount(), config.getIsEdit(), config.getTranSq(), config.getDisplay() };
			rowData[i] = t;

			smsMap.put(("" + config.getId()), "0");
			Calendar rightNow = Calendar.getInstance();
			Integer year = rightNow.get(Calendar.YEAR);
			Integer month = rightNow.get(Calendar.MONTH) + 1; // 第一个月从0开始，所以得到月份＋1
			Integer day = rightNow.get(Calendar.DAY_OF_MONTH);
			Integer TimeNow24 = year + month + day;
			smsTimeMap.put("" + config.getId(), TimeNow24);
		}

		configListTableModel = new ConfigListTableModel();
		configListTable = new JTable();
		configListTable.setModel(configListTableModel);
		configListTable.setPreferredScrollableViewportSize(new Dimension(250, 300));// 设置表格的大小
		configListTable.setRowHeight(30);// 设置每行的高度为20
		configListTable.addMouseListener(new MouseListener() {

			public void mouseReleased(MouseEvent e) {
			}

			public void mousePressed(MouseEvent e) {
			}

			public void mouseExited(MouseEvent e) {
			}

			public void mouseEntered(MouseEvent e) {
			}

			public void mouseClicked(MouseEvent e) {
				row = ((JTable) e.getSource()).rowAtPoint(e.getPoint()); // 获得行位置
				col = ((JTable) e.getSource()).columnAtPoint(e.getPoint()); // 获得列位置
				String cellVal = (String) (configListTableModel.getValueAt(row, 0)); // 获得点击单元格数据
				Config config = new Config();
				config.setId(Integer.parseInt(cellVal));
				updateConfigDetailTable(config);
				configListTable.updateUI();
			}
		});
		configListTable.setShowVerticalLines(true);// 是否显示垂直的网格线
		// configListTable.setValueAt("tt", 0, 0);// 设置某个单元格的值,这个值是一个对象
		configListTable.doLayout();
		configListTable.setBackground(new Color(255, 255, 255, 255));
		configListTable.getTableHeader().setFont(new Font("Dialog", 0, 14));
		// configDetailTable.setBounds(0, 0, 300,
		// rm.getScreenViewProp().getScreenHeight() -100);
		JScrollPane configListTableScrollpane = new JScrollPane(configListTable);
		// configListTable.addRowSelectionInterval(index0, index1);
		DefaultTableCellRenderer tcr = new DefaultTableCellRenderer();// 设置table内容居中
		// tcr.setHorizontalAlignment(JLabel.CENTER);
		tcr.setHorizontalAlignment(SwingConstants.CENTER);// 这句和上句作用一样
		configListTable.setDefaultRenderer(Object.class, tcr);

		this.add(configListTableScrollpane, BorderLayout.WEST);
	}

	// 更新配置详情列表
	public void updateConfigDetailTable(Config c) {
		Config config = configDao.select(c);
		String[] temp = { ("" + config.getId()), config.getConfigName(), config.getTableName(), config.getPhone(),
				config.getMessage(), config.getIsSendSms(), config.getTime(), config.getConfigSql(), config.getCount(),
				config.getIsEdit(), config.getTranSq(), config.getDisplay() };
		for (int i = 0; i < congfigNames.length; i++) {
			String[] t = { congfigNames[i], temp[i] };
			configDetailData[i] = t;
		}

		updateCheckList(config);
		updateConfigSqlList(config);
		configDetailTableModel = new ConfigDetailTableModel();
		configDetailTable.setModel(configDetailTableModel);
		configDisplayTableModel.fireTableDataChanged();
	}

	// 更新上部字段详细配置
	public void initConfigDetailTable(Config c) {
		Config config = configDao.select(c);
		if (config != null) {
			String[] temp = { ("" + config.getId()), config.getConfigName(), config.getTableName(), config.getPhone(),
					config.getMessage(), config.getIsSendSms(), config.getTime(), config.getConfigSql(),
					config.getCount(), config.getIsEdit(), config.getTranSq(), config.getDisplay() };
			for (int i = 0; i < congfigNames.length; i++) {
				String[] t = { congfigNames[i], temp[i] };
				configDetailData[i] = t;
			}
		}

		configDetailTableModel = new ConfigDetailTableModel();
		configDetailTable = new JTable();
		configDetailTable.setModel(configDetailTableModel);
		// configListTable.setPreferredScrollableViewportSize(new Dimension(300,
		// 500));// 设置表格的大小
		configDetailTable.setRowHeight(30);// 设置每行的高度为20
		configDetailTable.setShowVerticalLines(true);// 是否显示垂直的网格线
		configDetailTable.doLayout();
		configDetailTable.setBackground(new Color(255, 255, 255, 255));
		configDetailTable.getTableHeader().setFont(new Font("Dialog", 0, 14));
		JScrollPane scrollpane = new JScrollPane(configDetailTable);
		// configListTable.addRowSelectionInterval(index0, index1);

		// configDetailTable.getColumnModel().getColumn(1).setCellRenderer(new
		// CheckBoxRenderer());
		DefaultTableCellRenderer tcr = new DefaultTableCellRenderer();// 设置table内容居中
		// tcr.setHorizontalAlignment(JLabel.CENTER);
		tcr.setHorizontalAlignment(SwingConstants.CENTER);// 这句和上句作用一样
		configDetailTable.setDefaultRenderer(Object.class, tcr);
		configPanel.add(scrollpane);
	}

	// 更新下部字段匹配列表
	public void updateConfigSqlList(Config config) {
		List<ConfigSql> cs = configDao.selectSqlPage(config);
		for (int i = 0; i < configDetailSqlData.length; i++) {
			for (int j = 0; j < configDetailSqlData[i].length; j++) {
				configDetailSqlData[i][j] = null;
			}
		}
		for (int i = 0; i < cs.size(); i++) {
			ConfigSql tempCs = cs.get(i);
			String[] t = { tempCs.getMonitorField(), tempCs.getFieldName(), tempCs.getExactMatch(), tempCs.getValue() };
			configDetailSqlData[i] = t;
		}
		configSqlTableModel.fireTableStructureChanged();
	}

	// 更新展示字段列表
	public void updateCheckList(Config config) {
		Boolean[] displayArr = new Boolean[30];
		if (config != null) {
			String display = config.getDisplay();
			if (display == null) {
				display = "0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0";
			}
			String[] temp1 = display.split(",");
			// char[] temp =display.toCharArray();
			for (int i = 0; i < temp1.length; i++) {
				// String str = String.valueOf(temp[i]);
				if ("1".equals(temp1[i])) {
					displayArr[i] = true;
				} else {
					displayArr[i] = false;
				}
			}
		}
		for (int i = 0; i < checkConfigDisplay.length; i++) {
			Object[] t = { displayArr[i], checkConfigDisplay[i] };
			configDisplayData[i] = t;
		}
	}

	// 初始化下部字段匹配列表
	public void initConfigSqlTable(Config c) {
		List<ConfigSql> configSqls = configDao.selectSqlPage(c);
		if (configSqls != null && configSqls.size() != 0) {
			for (int i = 0; i < configSqls.size(); i++) {
				ConfigSql tempCs = configSqls.get(i);
				String[] t = { tempCs.getMonitorField(), tempCs.getFieldName(), tempCs.getExactMatch(),
						tempCs.getValue() };
				configDetailSqlData[i] = t;
			}
		}

		configSqlTableModel = new ConfigSqlTableModel();
		configSqlTable = new JTable();
		configSqlTable.setModel(configSqlTableModel);
		configSqlTable.setPreferredScrollableViewportSize(new Dimension(300, 500));// 设置表格的大小
		configSqlTable.setRowHeight(30);// 设置每行的高度为20
		configSqlTable.setShowVerticalLines(true);// 是否显示垂直的网格线
		configSqlTable.doLayout();
		configSqlTable.setBackground(new Color(255, 255, 255, 255));
		configSqlTable.getTableHeader().setFont(new Font("Dialog", 0, 14));
		JScrollPane scrollpane = new JScrollPane(configSqlTable);
		scrollpane.setBounds(0, 0, 500, 300);
		// configListTable.addRowSelectionInterval(index0, index1);
		DefaultTableCellRenderer tcr = new DefaultTableCellRenderer();// 设置table内容居中
		// tcr.setHorizontalAlignment(JLabel.CENTER);
		tcr.setHorizontalAlignment(SwingConstants.CENTER);// 这句和上句作用一样
		configSqlTable.setDefaultRenderer(Object.class, tcr);

		configPanel.add(scrollpane);
	}

	// 初始化右侧字段显示列表
	public void initConfigCheckList(Config c) {
		Config config = configDao.select(c);
		updateCheckList(config);

		configDisplayTableModel = new ConfigDisplayTableModel();
		configDisplayTable = new JTable();
		configDisplayTable.setModel(configDisplayTableModel);
		configDisplayTable.setPreferredScrollableViewportSize(new Dimension(300, 300));// 设置表格的大小
		configDisplayTable.setRowHeight(30);// 设置每行的高度为20
		configDisplayTable.setShowVerticalLines(true);// 是否显示垂直的网格线
		configDisplayTable.doLayout();
		configDisplayTable.setBackground(new Color(255, 255, 255, 255));
		configDisplayTable.getTableHeader().setFont(new Font("Dialog", 0, 14));
		DefaultTableCellRenderer tcr = new DefaultTableCellRenderer();// 设置table内容居中
		tcr.setHorizontalAlignment(SwingConstants.CENTER);// 这句和上句作用一样
		configDisplayTable.setDefaultRenderer(Object.class, tcr);

		JScrollPane busiListCheckScrollpane = new JScrollPane(configDisplayTable);
		busiListCheckScrollpane.setBounds(0, 0, 500, 300);
		configDisplayTable.getColumnModel().getColumn(0).setPreferredWidth(1);
		this.add(busiListCheckScrollpane, BorderLayout.EAST);
	}

	// 开始监控
	public void startMonitor() {
		timer.cancel();
		timer = new Timer();
		timer.schedule(new TimerTask() {
			public void run() {
				monitor();
			}
		}, 0, 10000);
	}

	public void endMonitor() {
		timer.cancel();
	}

	// 监控方法
	public void monitor() {
		List<Config> dataList = configDao.selectPage(null);
		Calendar rightNow = Calendar.getInstance();
		Integer year = rightNow.get(Calendar.YEAR);
		Integer month = rightNow.get(Calendar.MONTH) + 1; // 第一个月从0开始，所以得到月份＋1
		Integer day = rightNow.get(Calendar.DAY_OF_MONTH);
		Integer TimeNow24 = year + month + day;
		for (int i = 0; i < dataList.size(); i++) {
			
			Config config = dataList.get(i);
			String isSendSms = config.getIsSendSms();
			if ("是".equals(isSendSms) || "1".equals(isSendSms) || "true".equals(isSendSms) || "YES".equalsIgnoreCase(isSendSms)) {
//				if (!"".equals(config.getCount()) && config.getCount() != null) {
				if (true) {
					String num = "";
					try {
						boolean isSMMNTJNL = config.getTableName().contains("SMMNT_JNL") || config.getTableName().contains("smmnt_jnl")
								||config.getConfigSql().contains("SMMNT_JNL") || config.getConfigSql().contains("smmnt_jnl");
						String sql = "";
						if(isSMMNTJNL) {
							String[] sqls = config.getConfigSql().split("1=1");
							if (config.getTime() != null && !"".equals(config.getTime())) {
								sql = sqls[0] + "1=1"
										+ " and (TIME_STAMP > ((select to_char(systimestamp, 'yyyymmddhh24missff3') from dual) - (to_number("
										+ config.getTime() + " * 100000))))" + sqls[1];
							}
						}else {
							sql = config.getConfigSql();
						}
						num = busiMonitorDao.selectCount(sql);
					} catch (Exception e) {
						continue;
					}
					
					if (!"".equals(num) && num != null) {
						// 监控发送短信
						// 第二天重置短信状态为可发送
						if (smsTimeMap.get("" + config.getId()) < TimeNow24) {
							smsMap.put("" + config.getId(), "0");
							smsTimeMap.put("" + config.getId(), TimeNow24);
						}
						if ("0".equals(smsMap.get("" + config.getId()))) {
							try {
								// 获取当前目录
								URL url = this.getClass().getClassLoader().getResource(".");
								// 发送短信jar包
								String exec = url.getPath() + "lib/imcSms.jar";
								// 执行jar包方法的java命令
								String a = "java -cp " + exec + " com.imcSms.res.SmsUtil " + config.getPhone() + " "
										+ config.getMessage() + " " + config.getMessage() + " > c:\\\\1.log";
								logger.info(a);
								Runtime.getRuntime().exec(a);
								logger.info("sendSms" + config.getPhone() + " " + config.getMessage() + " "
										+ config.getMessage());
							} catch (Exception e) {
								logger.debug(e.toString());
							}
							// 短信发送后设置为不发送状态
							smsMap.put("" + config.getId(), "1");
						}
					}
				}
			}
		}
	}

	// 左侧配置列表Model
	class ConfigListTableModel extends AbstractTableModel {
		// 列数
		public int getColumnCount() {
			return columnNames.length;
		}

		// 行数
		public int getRowCount() {
			return rowData.length;
		}

		// 单元格数据
		public Object getValueAt(int row, int col) {
			return rowData[row][col];
		}

		public String getColumnName(int column) {
			return columnNames[column];
		}
	}

	// 中间列表上部详细配置列表Model
	class ConfigDetailTableModel extends AbstractTableModel {
		public int getColumnCount() {
			return 2;
		}

		public int getRowCount() {
			return configDetailData.length;
		}

		public Object getValueAt(int row, int col) {
			// JCheckBox jc = new JCheckBox();
			// if(row == 5 && col == 1) {
			// if("是".equals((String)configDetailData[row][col])) {
			// return true;
			// }else {
			// return false;
			// }
			// }
			return configDetailData[row][col];
		}

		public String getColumnName(int column) {
			return detailColumnNames[column];
		}

		/**
		 * 指定设置数据单元是否可编辑.这里设置"姓名","学号"不可编辑
		 */
		@Override
		public boolean isCellEditable(int rowIndex, int columnIndex) {
			if (columnIndex < 1) {
				return false;
			} else if (rowIndex == 0 && columnIndex == 1) {
				return false;
			} else {
				return true;
			}

		}

		/**
		 * 如果数据单元为可编辑，则将编辑后的值替换原来的值
		 */
		@Override
		public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
			configDetailData[rowIndex][columnIndex] = aValue;
			/* 通知监听器数据单元数据已经改变 */
			fireTableCellUpdated(rowIndex, columnIndex);
			// System.out.println(aValue);
			// System.out.println(configDetailData[rowIndex][columnIndex]);

		}

	}

	// 中间列表下部字段配置列表Model
	class ConfigSqlTableModel extends AbstractTableModel {
		public int getColumnCount() {
			return detailSqlColumnNames.length;
		}

		public int getRowCount() {
			return configDetailSqlData.length;
		}

		public Object getValueAt(int row, int col) {
			return configDetailSqlData[row][col];
		}

		public String getColumnName(int column) {
			return detailSqlColumnNames[column];
		}

		/**
		 * 指定设置数据单元是否可编辑.这里设置"姓名","学号"不可编辑
		 */
		@Override
		public boolean isCellEditable(int rowIndex, int columnIndex) {
			// if (columnIndex < 2) {
			// return false;
			// } else if (rowIndex == 0 && columnIndex == 2) {
			// return false;
			// } else {
			// return true;
			// }
			return true;
		}

		/**
		 * 如果数据单元为可编辑，则将编辑后的值替换原来的值
		 */
		@Override
		public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
			configDetailSqlData[rowIndex][columnIndex] = aValue;
			/* 通知监听器数据单元数据已经改变 */
			fireTableCellUpdated(rowIndex, columnIndex);
			// System.out.println(aValue);
			// System.out.println(configDetailData[rowIndex][columnIndex]);

		}
	}

	// 右侧展示选择列表
	class ConfigDisplayTableModel extends AbstractTableModel {
		Class[] typeArray = { Boolean.class, Object.class };

		public int getColumnCount() {
			return 2;
		}

		public int getRowCount() {
			return configDisplayData.length;
		}

		public Object getValueAt(int row, int col) {
			return configDisplayData[row][col];
		}

		public String getColumnName(int column) {
			return displayColumnNames[column];
		}

		/**
		 * 指定设置数据单元是否可编辑.这里设置"姓名","学号"不可编辑
		 */
		@Override
		public boolean isCellEditable(int rowIndex, int columnIndex) {
			return true;
		}

		/**
		 * 如果数据单元为可编辑，则将编辑后的值替换原来的值
		 */
		@Override
		public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
			configDisplayData[rowIndex][columnIndex] = aValue;
			/* 通知监听器数据单元数据已经改变 */
			fireTableCellUpdated(rowIndex, columnIndex);
			// System.out.println(aValue);
			// System.out.println(configDisplayData[rowIndex][columnIndex]);

		}

		// 实现了如果是boolean自动转成JCheckbox
		/*
		 * 需要自己的celleditor这么麻烦吧。jtable自动支持Jcheckbox，
		 * 只要覆盖tablemodel的getColumnClass返回一个boolean的class， jtable会自动画一个Jcheckbox给你，
		 * 你的value是true还是false直接读table里那个cell的值就可以
		 */
		public Class getColumnClass(int columnIndex) {
			return typeArray[columnIndex];// 返回每一列的数据类型
		}
	}

	// table添加checkbox，暂时不用
	class CheckBoxRenderer implements TableCellRenderer {

		public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,
				final int row, final int column) {
			if (row == 5 && column == 1) {
				// 创建用于返回的渲染组件
				final JCheckBox ck = new JCheckBox();
				// 使具有焦点的行对应的复选框选中

				ck.addChangeListener(new ChangeListener() {
					public void stateChanged(ChangeEvent e) {
						if ("1".equals(configDetailData[row][column])) {
							ck.setSelected(false);
							configDetailData[row][column] = "0";
						} else {
							ck.setSelected(true);
							configDetailData[row][column] = "1";
						}
						// System.out.println(configDetailData[row][column]);
					}
				});

				// 设置单选box.setSelected(hasFocus);
				// 使复选框在单元格内居中显示
				ck.setHorizontalAlignment((int) 0.5f);
				return ck;
			} else {
				JTextArea ja = new JTextArea((String) value);
				ja.setAlignmentX((int) 0.5f);
				// ja.setAlignmentY((int) 0.5f);
				return ja;
			}

		}
	}
}
